import redis.asyncio as aioredis
from common.logger import logger


class RedisManager:
    def __init__(self, redis_url: str = "redis://localhost:6379/0"):
        self.redis_url = redis_url
        self.redis: aioredis.Redis | None = None

    async def initialize(self) -> aioredis.Redis:
        """初始化 Redis 客户端"""
        logger.info("调用 RedisManager.initialize 函数")
        if not self.redis:
            self.redis = aioredis.from_url(
                self.redis_url,
                encoding="utf-8",
                decode_responses=True,
            )
        return self.redis

    async def close(self):
        """关闭 Redis 连接"""
        logger.info("关闭 Redis 客户端")
        if self.redis:
            await self.redis.close()
            self.redis = None
